using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using softDemo.Demain.Responsity;
using softDemo.basic.Responsity;
using softDemo.basic.Db;
using Microsoft.EntityFrameworkCore;
using softDemo.Demain.log;
using soft.softDemo.basic.Filter;
using Soft1ApiDemo.Infrastructure.Filters;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using System.Text;
using Microsoft.IdentityModel.Tokens;
using Soft1ApiDemo.Infrastructure.Parameter;
using Soft1ApiDemo.Infrastructure.File;

namespace softDemo.API
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();
            // 注册服务
            services.AddScoped(typeof(IFileUpload), typeof(FileUpload));

            //服务注册
            services.AddScoped(typeof(IResponsity<>), typeof(Responsity<>));

            // 数据库上下文服务注册
            // 注意：如果注册数据库上下文服务，数据库上下文类中一定要有有参构造函数。
            services.AddDbContext<DbSoft>(options =>
            {
                options.UseSqlServer(Configuration.GetConnectionString("SqlServer"));
            });

            // 注册服务
            services.AddScoped(typeof(IResponsity<>), typeof(Responsity<>));

            // 添加控制器全局过滤器服务
            services.AddControllers(options =>
            {
                // 注意：在.net cor中有多种过滤器可供我们使用，比如：异常过滤器、操作过滤器、资源过滤器、授权过滤器等
                // 它们都有不同的功能与作用。
                // 我们可以按需使用不同的过滤器。
                options.Filters.Add<MyCouterFilter>();   //添加异常过滤器
                options.Filters.Add<AuditLogFilter>();  //添加动作（操作）过滤器
            });

            // token
            // 注意：使用token，必须要添加依赖包：Microsoft.AspNetCore.Authentication.JwtBearer
            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
               .AddJwtBearer(option =>
               {
                   option.RequireHttpsMetadata = false; //配置是否为https协议
                   option.SaveToken = true;            //配置token是否保存在api上下文
                                                       // 注意：Get()用法：将配置实例绑定到实体类中（配置键 匹配 类属性）
                   var tokenParameter = Configuration.GetSection("TokenParameter").Get<TokenParameter>();
                   option.TokenValidationParameters = new TokenValidationParameters
                   {
                       ValidateIssuerSigningKey = true,
                       IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(tokenParameter.Secret)),
                       ValidIssuer = tokenParameter.Issuer,
                       ValidateIssuer = true,
                       ValidateAudience = false
                   };
               });
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            //注册认证中间件，必须在鉴权中间件前面
            app.UseAuthentication();
            app.UseAuthorization();
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseHttpsRedirection();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }
}
